package com.woniuxy.charin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.charin.mapper.ChargingPileMapper;
import com.woniuxy.charin.model.entity.ChargingGun;
import com.woniuxy.charin.model.entity.ChargingPile;
import com.woniuxy.charin.model.vo.PageResponse;
import com.woniuxy.charin.service.ChargingGunService;
import com.woniuxy.charin.service.ChargingPileService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 服务接口实现
 *
 * @author
 * @description
 * @since 2024-12-23 20:41:46
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class ChargingPileServiceImpl extends
        ServiceImpl<ChargingPileMapper, ChargingPile>
        implements ChargingPileService {
    @Autowired
    private ChargingPileMapper chargingPileMapper;

    @Autowired
    private ChargingGunService chargingGunService;

    //分页查询
    public PageResponse<ChargingPile> getChargingPileList(
            String pileName, String pileCode,  String pileStatus, int page, int size) {
        log.info("getChargingPileList: " +
                        "pileName={}, status={}, page={}, size={}",
                pileName, pileStatus, page, size);
        // 创建分页对象
        Page<ChargingPile> chargingPilePage = new Page<>(page, size);

        // 使用 LambdaQueryWrapper 拼装查询条件
        LambdaQueryWrapper<ChargingPile> wrapper = new LambdaQueryWrapper<>();

        // 如果 pileName 不为空，就加上模糊搜索
        if (pileName != null && !pileName.trim().isEmpty()) {
            wrapper.like(ChargingPile::getId, pileName.trim());
        }

        // 如果 pileCode 不为空，就加上模糊搜索
        if (pileCode != null && !pileCode.trim().isEmpty()) {
            wrapper.like(ChargingPile::getPileCode, pileCode.trim());
        }

        // 如果 status 不为 null，就加上 status 的条件
        if (pileStatus != null) {
            wrapper.eq(ChargingPile::getPileStatus, pileStatus);
        }

        // 如果 status 不为 null，就加上 status 的条件
        if (pileStatus != null) {
            wrapper.eq(ChargingPile::getPileStatus, pileStatus);
        }

        // 使用分页查询
        chargingPilePage = chargingPileMapper.selectPage(chargingPilePage, wrapper);

        // 返回查询到的记录
        return new PageResponse<>(chargingPilePage.getTotal(), chargingPilePage.getRecords());

    }

    public void deleteChargingPile(Integer id) {
        log.info("deleteChargingPile: {}", id);
        chargingPileMapper.deleteById(id);
    }

    public void addChargingPile(ChargingPile chargingPile) {
        log.info("addChargingPile: {}", chargingPile);
        chargingPileMapper.insert(chargingPile);
    }

    public void updateChargingPile(ChargingPile chargingPile) {
        log.info("updateChargingPile: {}", chargingPile);
        chargingPileMapper.updateById(chargingPile);
    }

    public List<ChargingPile> getChargingPileByStationId(Integer id) {
        log.info("getChargingPileByStationId: {}", id);
        LambdaQueryWrapper<ChargingPile> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ChargingPile::getStationId, id);
        return chargingPileMapper.selectList(wrapper);
    }

    @Override
    public List<ChargingPile> listByStationId(Long id) {
        log.info("listByStationId: {}", id);
        LambdaQueryWrapper<ChargingPile> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ChargingPile::getStationId, id);
        return chargingPileMapper.selectList(wrapper);
    }

    @Override
    public List<ChargingGun> createChargingPileWithChargingGuns(ChargingPile chargingPile, List<ChargingGun> chargingGuns) {
        this.save(chargingPile);
        chargingGuns.forEach(gun -> gun.setPileId(chargingPile.getId()));
        chargingGunService.saveBatch(chargingGuns);
        return chargingGuns;
    }

    @Override
    public List<ChargingGun> updateChargingPilesWithChargingGun(
            ChargingPile chargingPile, List<ChargingGun> chargingGuns) {
        if (chargingPile == null) {
            throw new IllegalArgumentException("Station 参数不能为空");
        }
        if (chargingPile.getId() == null) {
            throw new IllegalArgumentException("Station ID 不能为空");
        }

        System.out.println("Updating chargingPile: " + chargingPile);

        // 更新站点信息
        boolean chargingPileUpdated = this.updateById(chargingPile);
        if (!chargingPileUpdated) {
            throw new RuntimeException("更新站点信息失败: " + chargingPile.getId());
        }

        // 获取现有充电枪列表
        List<ChargingGun> existingGun = chargingGunService.listByChargingPileId(chargingPile.getId());

        // 删除不存在的充电枪
        List<Long> newGunIds = chargingGuns.stream()
                .map(ChargingGun::getId)
                .filter(Objects::nonNull)
                .collect(Collectors.toList());

        existingGun.stream()
                .filter(gun -> !newGunIds.contains(gun.getId()))
                .forEach(gun -> {
                    boolean removed = chargingGunService.removeById(gun.getId());
                    if (!removed) {
                        throw new RuntimeException("删除充电桩失败: " + gun.getId());
                    }
                });

        // 更新或新增充电枪
        for (ChargingGun gun : chargingGuns) {
            if (gun.getId() == null) {
                gun.setPileId(chargingPile.getId());
            }

            if (gun.getId() != null) {
                if (!chargingGunService.updateById(gun)) {
                    throw new RuntimeException("更新充电枪失败: " + gun.getId());
                }
            } else {
                boolean gunSaved = chargingGunService.save(gun);
                if (!gunSaved) {
                    throw new RuntimeException("新增充电枪失败");
                }
            }
        }
        return chargingGuns;
    }

    @Override
    public void offlineChargingPile(int id) {
        log.info("offlineChargingPile: {}", id);
        ChargingPile chargingPile = chargingPileMapper.selectById(id);
        chargingPile.setPileStatus("空闲中");
        chargingPileMapper.updateById(chargingPile);
    }

    //故障中
    @Override
    public void setChargingPileCracked(int id) {
        log.info("setChargingPileCracked: {}", id);
        ChargingPile chargingPile = chargingPileMapper.selectById(id);
        chargingPile.setPileStatus("故障中");
        chargingPileMapper.updateById(chargingPile);
    }

    @Override
    public void onlineChargingPile(int id) {
        log.info("onlineChargingPile: {}", id);
        ChargingPile chargingPile = chargingPileMapper.selectById(id);
        chargingPile.setPileStatus("使用中");
        chargingPileMapper.updateById(chargingPile);
    }

    @Override
    public ChargingPile getChargingPileById(Integer id) {
        log.info("getChargingPileById: {}", id);
        return chargingPileMapper.selectById(id);
    }
}